﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using MidiDecoder;
using NAudio.Wave;
using SimpleFMMatrix.DataStructures;

namespace SimpleFMMatrix.ViewModel
{
    public class ConvertMidiFileCommand : ICommand
    {
        private FMMatrix matrix;

        public ConvertMidiFileCommand(FMMatrix _matrix)
        {
            matrix = _matrix;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged = delegate { };

        public void Execute(object parameter)
        {
            var window = parameter as Window;
            if (window == null) return;

            var opendialog = new Microsoft.Win32.OpenFileDialog();
            opendialog.Filter = "MIDI File (*.mid)|*.mid";
            if (!opendialog.ShowDialog(window).Value) return;

            MIDI midi = null;
            FileStream midistream = null;
            try
            {
                midistream = new FileStream(opendialog.FileName, FileMode.Open, FileAccess.Read);
                midi = MIDI.FromStream(midistream);
            }
            catch (MidiFileFormatException ex)
            {
                MessageBox.Show(window, "Error parsing midi file: \r\n" + ex.Message, "MidiFileFormatException", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(window, "Error parsing midi file: \r\n" + ex.Message, "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            finally
            {
                if (midistream != null)
                    midistream.Close();
            }

            var savedialog = new Microsoft.Win32.SaveFileDialog();
            savedialog.Filter = "Wave File (*.wav)|*.wav";
            if (!savedialog.ShowDialog(window).Value) return;

            MidiOperations.ConvertAndWriteToWave(midi, matrix, savedialog.FileName);
        }
    }
}
